﻿/*******************************************************************************
 * Copyright © 2025 CKS.Core.Framework 版权所有
 * Author: 云海
 * Description: 
 * 
*********************************************************************************/
using Infrastructure.Extensions;
using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;

namespace CKS.Core.Framework
{
    public static class Configs
    {
       public static XmlDocument xdconfig { get; set; }
        private static string LastMd5 = "";
        static Configs() {
            xdconfig = new XmlDocument();
            LoadConfig();
        }

        private static string FilePath = "";
        /// <summary>
        /// 加载config/config.xml
        /// </summary>
        public static void LoadConfig()
        {
            try
            {
                string filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory , "config\\config.xml"); // HttpContext.Current.Server.MapPath("~/config/config.xml");

                FilePath = filePath;

                string localMd5= GetMD5HashFromFile(filePath);
                if (LastMd5.IsEmpty())
                {
                    LastMd5 = localMd5;
                    LoadConfigFromFile(localMd5);
                }
                else if (!LastMd5.Equals(localMd5))
                {
                    LastMd5 = localMd5;
                   // Log.Log.Info("检测到配置更改了");
                    LoadConfigFromFile(localMd5);

                }
              
            }
            catch (System.Exception ex)
            {
                LastMd5 = "";
                xdconfig = new XmlDocument();
                //Log.Log.Info("LoadConfig异常:" + ex.Message);
            }
        }

        public static void LoadConfigFromFile(string localMd5)
        {
         
            //复制到新文件
            string sourceName = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory , "config\\config.xml"); // HttpContext.Current.Server.MapPath("~/config/config.xml");

            string destName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "config\\X" + Guid.NewGuid().ToString().Replace("-", "") + ".xml");
            System.IO.File.Copy(sourceName, destName);
            xdconfig.Load(destName);
            
            System.IO.File.Delete(destName);
        }



        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        public static string GetValue(string key)
        {
            try
            {
                return (xdconfig.SelectSingleNode($"//appSettings/add[@key='{key}']") as XmlElement).GetAttribute("value");
            }
            catch (System.Exception)
            {

                return "";
            }
        }
        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
          
            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xdconfig.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
            if (xElem1 != null) xElem1.SetAttribute("value", value);
            else
            {
                xElem2 = xdconfig.CreateElement("add");
                xElem2.SetAttribute("key", key);
                xElem2.SetAttribute("value", value);
                xNode.AppendChild(xElem2);
            }
            xdconfig.Save(FilePath);
        }

        /// <summary>
        /// 获取指定AppSetting节点的值
        /// </summary>
        /// <param name="sectname">节点名称</param>
        /// <param name="key">子节点名称</param>
        /// <returns></returns>
        public static string GetAppSetting(string sectname, string key)
        {
            try
            {
              
                var xd = xdconfig.Clone();
                var node = xd.SelectSingleNode($"//appSettings[@name='{sectname}']/add[@key='{key}']");
                if (node == null)
                    return "";
                XmlElement xe = node as XmlElement;
                return xe.GetAttribute("value");
            }
            catch (System.Exception)
            {
                return "";
            }

        }

        /// <summary>
        /// 获取appSettings的子节点集合。 
        /// </summary>
        /// <param name="sectname"></param>
        /// <param name="cname"></param>
        /// <returns></returns>
        public static XmlNodeList GetAppSettingXmlNodeList(string sectname,string cname)
        {
            var xd = xdconfig.DocumentElement.Clone();
            var nodes = xd.SelectNodes($"//appSettings[@name='{sectname}']/{cname}/Package");
            return nodes;
        }

        /// <summary>
        /// 获取数据库配置
        /// </summary>
        /// <param name="name"></param>
        /// <returns>dbType: 0 Mysql ,1 SqlServer </returns>
        public static (string connectionString,int dbType) GetConnectionString(string name)
        {
            (string connectionString, int dbType) res = ("",0);
            try
            {
              
                var xd = xdconfig.Clone();
                var node = xd.SelectSingleNode($"//configuration/connectionStrings/add[@name='{name}']");
                if (node == null)
                    return res;
                XmlElement xe = node as XmlElement;
                res.connectionString = xe.GetAttribute("connectionString");
                res.dbType = xe.GetAttribute("dbType").ParseToInt();
                return res;
            }
            catch (System.Exception)
            {
                return res;
            }
        }


        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                
                MemoryStream file = new MemoryStream(File.ReadAllBytes(fileName));
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                // throw new Exception(“GetMD5HashFromFile() fail, error:” +ex.Message);
               // Log.Log.Info("获取文件MD5失败"+ex.Message);
                return "";
            }
        }

    }
}
